package com.akuma.swing.plugin;

import com.akuma.redmine.entity.ProjectsQuery;
import com.akuma.redmine.service.IProjectService;
import com.akuma.redmine.service.impl.ProjectServiceImpl;

import javax.swing.*;
import java.awt.*;

/**
 * Created by akuma on 2016/10/20.
 *
 * @author akuma
 */
public class ProjectWinPlugin {
    private static IProjectService projectService = new ProjectServiceImpl();

    public static void allSelect(Container con) {
        allSelect(null, null, con, 0, 0);
    }

    public static void allSelect(Integer width, Integer height, Container con) {
        allSelect(width, height, con, 0, 0);
    }

    public static void allSelect(Container con, Integer left, Integer top) {
        allSelect(0, 0, con, left, top);
    }

    public static void allSelect(Integer width, Integer height, Container con, Integer left, Integer top) {
        ProjectsQuery all = projectService.findAll();
        JComboBox projectsNamesBox = new JComboBox(all.names());
        if (width != null && height != null) {
            projectsNamesBox.setSize(width, height);
        }
        projectsNamesBox.setLocation(left, top);
        con.add(projectsNamesBox);
    }

    public static void projectTable(Container con,Object controller) {
        projectTable(null, null, con,controller, 0, 0);
    }

    public static void projectTable(Integer width, Integer height, Container con,Object controller ) {
        projectTable(width, height, con,controller, 0, 0);
    }

    public static void projectTable(Container con, Object controller, Integer left, Integer top) {
        projectTable(0, 0, con,controller, left, top);
    }

    public static void projectTable(Integer width, Integer height, Container con, Object controller, Integer left, Integer top) {
        ProjectsQuery all = projectService.findAll();
        String[] names = new String[]{"id", "name", "desc", "操作"};
        Object[][] table = all.table();
        JTable projectTable = new JTable(addController(table, controller), names);
        JScrollPane jScrollPane = new JScrollPane(projectTable);
        if (width != null && height != null) {
            projectTable.setSize(width, height);
            jScrollPane.setSize(left, top);
        }
        jScrollPane.setLocation(left, top);
        con.add(jScrollPane);
    }

    private static Object[][] addController(Object[][] objects, Object controller) {
        if (objects == null || objects.length == 0) {
            return objects;
        }
        for (int i = 0; i < objects.length; i++) {
            Object[] source = objects[i];
            objects[i] = new Object[source.length + 1];
            for (int j = 0; j < source.length; j++) {
                objects[i][j] = source[j];
            }
            objects[i][source.length] = controller;
        }
        return objects;
    }
}
